<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body,html {padding:0;margin:0}
    #c {
      border: 1px solid #f00;
    }
    #img {
      display: none;
    }
    .rect {
      position: absolute;
      width: 10px;
      height: 10px;
      left: 0;
      top: 0;
      transform-origin: 0 0;
      background: rgba(0,0,0,1);
      border: 1px solid #fff;
      display: none;
    }
    .container {
      position: relative;
      left:0;
      top: 0;
      width: 400px;
      height: 267px;
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <div class="container">
    <canvas id="c" width="400px" height="267px"></canvas>
    <div class="rect"></div>
  </div>
  <button onclick="saveImg()">保存</button>
  <script>
    let canvas = document.querySelector("#c");
    let ctx = canvas.getContext("2d");
    let rect = document.querySelector(".rect");
    let container = document.querySelector('.container')
    let img = new Image();
    let s = false;
    img.src="../images/dama/1.jpg"
    img.onload = ()=>{
      ctx.drawImage(img,0,0,400,267);
    }

    container.onmouseleave = ()=>{
      rect.style.display = "none"
    }
    container.onmousedown = ()=>{
      container.addEventListener("mousemove",mouseDama)
    }
    container.addEventListener('mousemove',rectMove)
    container.onmouseup = ()=>{
      container.removeEventListener("mousemove",mouseDama);
    };

    function saveImg() {
      let a = document.createElement('a')
      a.href = canvas.toDataURL("image/png");
      a.download = "图片";
      a.click();
    }
    function rectMove(e) {
      let {pageX,pageY} = e;
      rect.style=`display:block;background:${getColor(ctx,pageX,pageY)};transform: translate(${pageX}px,${pageY}px)`;
    }
    function mouseDama(e) {
      s = true;
      dama(ctx,e.pageX,e.pageY)
    }
    function dama(ctx,x,y) {
      ctx.fillStyle = getColor(ctx,x,y)
      ctx.fillRect(x,y,10,10)
    }
    function getColor(ctx,x,y) {
      let imgData = ctx.getImageData(s ? x+10: x, y, 1, 1);
      let [r,g,b,a] = imgData.data;
      return `rgba(${r},${g},${b},${a})`;
    }
  </script>
</body>
</html>